package com.example.wanandroid.activity.main.home

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup

class BannerView(private val context: Context, attributeSet: AttributeSet? = null) :
    ViewGroup(context, attributeSet) {
    private var lastX = 0
    private var curPosition = 0
    private var banners: List<View> = ArrayList()
    private var canScroll = true
    private var offsetX = 0
    private var onceLayout=true

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        MeasureSpec.getMode(widthMeasureSpec)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        if (banners.size >= 2 && onceLayout) {
            layoutBanners(offsetX)
            startScroll()
            onceLayout = false
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event == null)
            return false

        val x = event.x.toInt()
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                canScroll = false
                lastX = x
            }

            MotionEvent.ACTION_MOVE -> {
                offsetX = x - lastX
                layoutBanners(offsetX)
            }

            MotionEvent.ACTION_UP -> {
//                if (offsetX >= width / 2) { //右移过界
//                    curPosition--
//                    setupBanners()
//                } else if (offsetX <= -width / 2) { //左移过界
//                    curPosition++
//                    setupBanners()
//                }
//                offsetX = 0
//                layoutBanners(offsetX)

                canScroll = true
            }
        }
        return true
    }

    /**
     * 设置Banners左右移动
     */
    private fun layoutBanners(offset:Int) {
        getChildAt(0).layout(
            left - width + offset,
            top,
            right - width + offset,
            bottom
        )
        getChildAt(1).layout(left + offset, top, right + offset, bottom)
        getChildAt(2).layout(
            left + width + offset,
            top,
            right + width + offset,
            bottom
        )
    }

    /**
     * 设置3个layout位置，每个layout位置放置一个view
     */
    private fun setupBanners() {
        if (curPosition <= -1) {
            curPosition = banners.size - 1
        } else if (curPosition >= banners.size) {
            curPosition = 0
        }

        setupPreView()
        setupCurView()
        setupNextView()
    }

    private fun setupCurView() {
        val curChild = banners[curPosition]
        val parent = curChild.parent
        if (parent != null) {
            (parent as ViewGroup).removeView(curChild)
        }
        addView(
            curChild,
            1,
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        )
    }

    private fun setupPreView() {
        val prePosition = if (curPosition <= 0) {
            banners.size - 1
        } else {
            curPosition - 1
        }
        val preChild = banners[prePosition]
        val parent = preChild.parent
        if (parent != null) {
            (parent as ViewGroup).removeView(preChild)
        }
        addView(
            preChild,
            0,
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        )
    }

    private fun setupNextView() {
        val nextPosition = if (curPosition >= banners.size - 1) {
            0
        } else {
            curPosition + 1
        }
        val nextChild = banners[nextPosition]
        val parent = nextChild.parent
        if (parent != null) {
            (parent as ViewGroup).removeView(nextChild)
        }
        addView(
            nextChild,
            2,
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        )
    }

    fun setBanners(banners: List<View>) {
        this.banners = banners
        setupBanners()
    }

    private fun startScroll() {
        val handler = object : Handler(context.mainLooper) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                offsetX -= 100
                if (offsetX <= -width){
                    offsetX = 0
                    curPosition++
                    setupBanners()
                }
                layoutBanners(offsetX)
            }
        }

        //每隔200ms发送一次
        Thread {
            while (true) {
                Thread.sleep(200)
                if (canScroll) {
                    handler.sendEmptyMessage(1)
                }
            }
        }.start()
    }

}